package com.spring.security.config;

import com.spring.security.filter.ResourceAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

@EnableResourceServer
@Configuration
public class ResourceAuthorzationConfig extends ResourceServerConfigurerAdapter {


    @Autowired
    private ResourceAuthorizationFilter resourceAuthorizationFilter;
    @Autowired
    private DataSource dataSource;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .requestMatchers().antMatchers("/auth/**");
        http.addFilter(resourceAuthorizationFilter);
    }
    @Bean
    public ClientDetailsService clientDetails() {
        //从数据库获取客户端注册信息
        return new JdbcClientDetailsService(dataSource);
    }


    @Bean
    public TokenStore tokenStore(){

        return new JdbcTokenStore(dataSource);
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore());
        resources.resourceId("resource-center");


    }

}
